package.cpath = "luaclib/?.so;3rd/lua-cjson/?.so;"
local skynet = require "skynet"
local json = require "cjson"
require "skynet.manager"	-- import skynet.register
require "config_redis"
local httpc = require "http.httpc"
local dns = require "dns"
local mysql = require "mysql"
local md5 = require "md5"

CMD = {}

local mysql_db
local function start_mysql(args)
    local function on_connect(db)
        db:query("set charset " .. args.charset);
    end
    mysql_db = mysql.connect {
        host    = args.host,
        port    = args.port,
        database = args.database,
        user    = args.user,
        password = args.password,
        max_packet_size = 1024 * 1024,
        on_connect = on_connect,
    }
end

---------------------------------begin mysql function---------------------------------
function goto_mysql_db_query(sql)
    return mysql_db:query(sql)
end

function mysql_db_query(sql)
    -- return mysql_db:query(sql)   
    -- local c = mysql_db:query('select database();')  
    --    print('====mysql_db_query===111111============',json.encode(c))
    local success, c = pcall(goto_mysql_db_query, sql)
    if success then
        if c.errno ~= nil then
            mysql_db:disconnect()
            start_mysql(mysql_args)
            success, c = pcall(goto_mysql_db_query, sql)
        end
        -- print('====mysql_db_query===============',json.encode(c))
        return c
    else
        -- print('====22222222222222===============',json.encode(c))
        mysql_db:disconnect()
        start_mysql(mysql_args)
        return goto_mysql_db_query(sql)
    end
end

function CMD.mysql_get_one(sql)
    local ok = false
    sql = sql .. ' limit 0,1'
    local res = mysql_db_query(sql)
    if #res == 0 then
        return ok
    end
    ok = true
    return res[1]
end

function CMD.mysql_get_all(sql)
    local ok = false
    local res = mysql_db_query(sql)
    if #res == 0 then
        return ok
    end
    return res
end

function CMD.mysql_insert(sql)
    local res = mysql_db_query(sql)
    local ok = false
    if res and res.errno then
        return ok
    end
    ok = res.insert_id
    return ok
end

function CMD.mysql_update(sql)
    mysql_db_query(sql)
end

function CMD.mysql_del(sql)
    mysql_db_query(sql)
end

function CMD.get_mid(uid)
    local status, body = httpc.get(server_url, '/game/backend/get_user?uid=' .. uid, {}, {})
    if status == 200 then
        print('============get_mid===============', body)
        return json.decode(body)
    else
        return nil
    end
end


function CMD.login_auth_wechat(form)
    local respheader = {}
    local status, body = httpc.post('shao.91laoyou.com', '/wechat.php', form, respheader);
    if status == 200 then
        local rearr = json.decode(body)
        if rearr.ret == 0 then
            return rearr.info, rearr.expires_time, rearr.password
        else
            return 2
        end
    else
        return 1
    end
end

function CMD.get_gps_addrs(a, b)
    local status, body = httpc.get(login_url, '/get_gps_addr.php?a=' .. a .. '&b=' .. b, {}, {})
    if status == 200 then
        -- print('============get_gps_addrs===============',body) 
        return body
    else
        return ''
    end
end
function CMD.get_user_debug(uid)
    local status, body = httpc.get(server_url, '/game/font/get_user?_debug_mid=' .. uid, {}, {})
    if status == 200 then
        skynet.error("-- login -- CMD.get_user_debug -------> body:", body)
        return json.decode(body)
    else
        return nil
    end
end

function CMD.get_pic(url)
    print('============get_pic=======111========', url)
    local status, body = httpc.get('ws.121youxi.net', '/head/post.php?url=' .. url, {}, {})
    if status == 200 then
        print('============get_pic=======2222========', body)
        return body
    else
        return nil
    end
end

function CMD.get_mid(uid)
    local status, body = httpc.get(server_url, '/game/backend/get_user?uid=' .. uid, {}, {})
    if status == 200 then
        print('============get_mid===============', body)
        return json.decode(body)
    else
        return nil
    end
end

function CMD.get_user_info(form)
    form.uid = math.floor(form.uid)
    skynet.error("-- login -- CMD.get_user_info -------> ", server_url .. '/game/backend/get_user?uid=' .. form.uid .. '&token=' .. form.token)
    local status, body = httpc.get(server_url, '/game/backend/get_user?uid=' .. form.uid .. '&token=' .. form.token, {}, {})
    if status == 200 then
        skynet.error("-- login -- CMD.get_user_info resurt -------> ", body)
        return json.decode(body)
    else
        return nil
    end
end

function CMD.use_room_card(form)
    -- local status, body = httpc.post(server_url,'/game/backend/use_room_card',form, {} );
    -- if status == 200 then
    -- 	print('============use_room_card===============',body) 
    -- 	return 1 
    -- else
    -- 	return 0
    -- end
end

function CMD.get_uid_card(uid)
    local query_sql = string.format("select * from `pan_game_room_card` where uid = %d", uid)
    -- print(query_sql)
    local user_record = mysql_db_query(query_sql)
    local card = 0
    if user_record[1] ~= nil and user_record[1].room_card ~= nil then
        card = user_record[1].room_card
    end
    return card
end

function CMD.update_game_card(data)
    -- print('update_game_card======LOGIN==================='..json.encode(data))
    local update_sql = string.format("update `pan_game_room_card` set room_card = room_card + %d where uid = %d", data.add_card_num, data.uid)
    -- print(update_sql)
    local res = mysql_db_query(update_sql)

    local query_sql = string.format("select * from `pan_game_room_card` where uid = %d", data.uid)
    -- print(query_sql)
    local user_record = mysql_db_query(query_sql)
    data.card_left = 0
    if user_record[1] ~= nil and user_record[1].room_card ~= nil then
        data.card_left = user_record[1].room_card
    end
    CMD.insert_game_card_log(data)
end

function CMD.insert_game_card_log(data)
    local ok = 0
    local time = os.date("%Y-%m-%d %H:%M:%S")
    if data.room_id == nil then
        data.room_id = 0
    end
    local table_name = 'pan_game_room_card_log_' .. string.sub(data.uid, -1)
    local query_sql = string.format("insert into %s (uid,room_card_change,room_card_after,message_id,create_time,room_id,text,flag)  values ( %d, %d,%d, %d,'%s',%d,'%s',0)",
    table_name, data.uid, data.add_card_num, data.card_left, data.gameType, time, data.room_id, json.encode(data))
    -- print(query_sql)
    local res = mysql_db_query(query_sql)
    if res and res.errno then
        return ok
    end
    ok = res.insert_id
    return ok
end

function CMD.update_game_card_log(data)
    local ok = 0
    if data.room_id ~= nil and data.room_id > 0 then
        local table_name = 'pan_game_room_card_log_' .. string.sub(data.uid, -1)
        local query_sql = string.format("update %s set message_id = message_id - 2000 where uid=%d and room_id=%d and message_id > 2000 and message_id < 3000",
        table_name, data.uid, data.room_id)
        -- print(query_sql)
        local res = mysql_db_query(query_sql)
    end
end

function CMD.update_game_coins(data)
    -- print('update_game_coins======LOGIN==================='..json.encode(data))
    local update_sql = string.format("update `pan_coins` set coins = coins + %d where uid = %d", data.uid, data.coins)
    local res = mysql_db_query(update_sql)

    local query_sql = string.format("select * from `pan_coins` where uid = %d", data.uid)
    -- print(query_sql)
    local user_record = mysql_db_query(query_sql)
    data.coins_old = 0
    data.coins_left = 0
    if user_record[1] ~= nil and user_record[1].coins ~= nil then
        data.coins_left = user_record[1].coins
        data.coins_left = data.coins_left - data.coins
    end
    CMD.insert_game_coins_log(data)
end

function CMD.insert_game_coins_log(data)
    local ok = 0
    local time = os.date("%Y-%m-%d %H:%M:%S")

    local table_name = 'pan_coins_log_' .. string.sub(data.uid, -1)
    local query_sql = string.format("insert into %s (uid,coins,coins_change,coins_after,create_time)  values ( %d, %d,%d, %d,'%s')",
    table_name, data.uid, data.coins_old, data.coins, data.coins_left, data.gameType, time)
    -- print(query_sql)
    local res = mysql_db_query(query_sql)
    if res and res.errno then
        return ok
    end
    ok = res.insert_id
    return ok
end

-- local game_to_type = {}
-- game_to_type[130] = 1
-- game_to_type[226] = 2
-- game_to_type[218] = 3
-- game_to_type[210] = 4
-- game_to_type[224] = 5
-- game_to_type[220] = 6
-- game_to_type[222] = 7
-- game_to_type[214] = 8
-- game_to_type[212] = 9
-- game_status 
-- 1	正在进行中，刚刚创建房间或游戏中
-- 2	上报每局游戏情况
-- 3	游戏取消，只创建房间未进行游戏
-- 4	游戏结束或者解散
function CMD.post_game_info(data, game_status)
    -- data.game_type = game_to_type[data.gameType]     
    data.game_type = data.gameType
    data.game_status = game_status
    -- print('============post_game_info=====111==from========',json.encode({data=json.encode(data)})) 
    -- skynet.call("MG_SAVE", "lua", "redis_rpush", 'game_log', json.encode(data)) 
    if game_status > 1 and data.setting.fang_zhu_ka_log_id ~= nil then
        local is_one = 1
        if game_status == 3 and data.number == 1 then
            is_one = 0
            CMD.update_game_card({ gameType = data.gameType + 10000, uid = data.create_uid, create_uid = data.create_uid, add_card_num = data.setting.fang_ka })
            --游戏没开始 退回房主 房卡 
            -- skynet.call("MG_SAVE", "lua", "return_fang_ka",data.create_uid,is_one,data.setting.fang_zhu_ka_log_id) 
        end
    end
    --游戏结束
    if game_status == 4 then
        if data.setting.pay_type == 1 and data.setting.fang_ka > 0 then
            CMD.update_game_card_log({ uid = data.create_uid, room_id = data.room_id })
            local card_log_logg = clone(data.setting)
            card_log_logg.card = -data.setting.fang_ka
            card_log_logg.uid = data.setting.create_uid
            skynet.call("MG_SAVE", "lua", "redis_rpush", 'card_log_to_redis', json.encode(card_log_logg))

        end
        local save_user_game_log = {}
        save_user_game_log.game_type = data.game_type
        for i, v in pairs(data.result) do
            save_user_game_log.uid = v.uid
            save_user_game_log.score = v.score
            skynet.call("MG_SAVE", "lua", "save_user_game_log", save_user_game_log)
        end
    end
    CMD.update_game_log(data, game_status)
end

local game_log_detail = {}
local game_log_pan_h5_games_log = {}
function CMD.insert_game_log(data)
    local ok = 0
    local time = data.create_date
    local query_sql = string.format("insert into `pan_h5_games` (game_type,room_id,game_status,creator_mid, creator, participant,setting, result,detail,create_time,update_time,game_url)  values ( %d, %d, %d,%d, '%s','%s','%s',   '%s','%s','%s','%s','%s')",
    data.gameType, data.room_id, 1, data.create_uid,
    json.encode(data.creator), '', json.encode(data.setting),
    '', '', time, time, data.game_url);
    local res = mysql_db_query(query_sql)
    if res and res.errno then
        return ok
    end
    ok = res.insert_id
    if game_log_pan_h5_games_log[res.insert_id] == nil then
        game_log_pan_h5_games_log[res.insert_id] = {}
    end
    local race_type = 0
    if data.race ~= nil and data.race > 0 then
        race_type = 1
    end
    local table_name = 'pan_h5_games_log_' .. string.sub(data.create_uid, -1)
    local query_sql = string.format("insert into %s (uid,game_id,score,type,create_time)  values ( %d, %d,0,%d,'%s')",
    table_name, data.create_uid, res.insert_id, race_type, time)
    local raees = mysql_db_query(query_sql)
    game_log_pan_h5_games_log[res.insert_id][data.create_uid] = raees.insert_id
    return ok
end

function CMD.update_game_log(data, game_status)
    local ok = 0
    local time = data.create_date
    if data.game_log_id > 0 then
        if game_log_pan_h5_games_log[data.game_log_id] == nil then
            game_log_pan_h5_games_log[data.game_log_id] = {}
        end
        local race_type = 0
        if data.race ~= nil and data.race > 0 then
            race_type = 1
        end
        for i, v in pairs(data.participant) do
            if game_log_pan_h5_games_log[data.game_log_id][v.uid] == nil then
                local table_name = 'pan_h5_games_log_' .. string.sub(v.uid, -1)
                local query_sql = string.format("insert into %s (uid,game_id,score,type,create_time)  values ( %d, %d,0,%d,'%s')",
                table_name, v.uid, data.game_log_id, race_type, time)
                local raees = mysql_db_query(query_sql)
                game_log_pan_h5_games_log[data.game_log_id][v.uid] = raees.insert_id
            end
        end
        if game_log_detail[data.game_log_id] == nil then
            game_log_detail[data.game_log_id] = {}
        end
        if data.detail ~= nil and data.detail ~= {} and data.number > 0 then
            if game_status == 2 then
                local data_need_2 = {}
                local score_1 = 0  --正分 
                local score_2 = 0   --负分
                for i, v in pairs(data.detail) do
                    local table_name = 'pan_h5_games_log_' .. string.sub(v.uid, -1)
                    local query_sql = string.format("update %s set score=score + %d where id = %d", table_name, v.score, game_log_pan_h5_games_log[data.game_log_id][v.uid])
                    mysql_db_query(query_sql)
                    -- print('============================data====================================',json.encode(data))
                    if game_status == 2 and ((data.setting.club_id ~= nil and data.setting.club_id > 0) or data.setting.club_type == 2 or data.setting.club_type == 5) then
                        local user_log = {}
                        user_log.club_id = data.setting.club_id
                        user_log.uid = v.uid
                        user_log.score = v.score
                        user_log.name = v.nickname
                        user_log.head = v.headurl
                        user_log.room_id = data.room_id
                        user_log.game_type = data.setting.game_type
                        user_log.cur_ju = data.number
                        user_log.time = os.time()
                        user_log.text = {}
                        if v.text_log_user ~= nil then
                            user_log.text.text_log_user = v.text_log_user
                        end
                        if (data.setting.club_id ~= nil and data.setting.club_id > 0) or data.setting.club_type == 5 then
                            if user_log.club_id == nil then
                                user_log.club_id = 0
                            end
                            skynet.call("MG_SAVE", "lua", "insert_club", 0, 5, user_log)
                        end

                        if data.setting.ji_fen_time ~= nil then
                            local data_fmc = {}
                            data_fmc.uid = v.uid
                            data_fmc.ji_fen_time = data.setting.ji_fen_time
                            data_fmc.type = data.game_type
                            data_fmc.room_id = data.room_id
                            data_fmc.bean = v.score - data.setting.ji_fen_time
                            data_fmc.club_id = data.setting.club_id
                            data_fmc.score = v.score
                            data_fmc.text = { room_id = data.room_id, create_uid = data.create_uid, cur_ju = data.number, ji_fen_time = data.setting.ji_fen_time, club_id = data.setting.club_id, score = v.score }
                            if v.text_log_user ~= nil then
                                data_fmc.text.text_log_user = v.text_log_user
                            end
                            --欢乐豆
                            if data.setting.club_type == 2 or data.setting.club_type == 5 then
                                if v.score < 0 then
                                    local bean_rs = skynet.call("MG_SAVE", "lua", "update_bean_uid", v.uid, data_fmc)
                                    if bean_rs > 0 then
                                        score_2 = score_2 + bean_rs - data.setting.ji_fen_time
                                    end
                                else
                                    score_1 = score_1 + v.score
                                    table.insert(data_need_2, data_fmc)
                                end
                            end
                            --积分
                            if data.setting.club_type == 3 then
                                skynet.call("MG_SAVE", "lua", "update_club", 0, 12, data_fmc)
                                skynet.call("CLUB", "lua", "update_club_user_score", data_fmc.uid, data_fmc.club_id, data_fmc.score)
                            end
                        end
                    end
                end

                --分数不够扣,赢家分数按比例扣减
                if data.setting.club_type == 2 or data.setting.club_type == 5 then
                    local score_lv = score_2 / score_1
                    for i, v in pairs(data_need_2) do
                        v.score_old = v.score
                        if score_lv < 1 then
                            v.score = math.floor(v.score * score_lv)
                            score_2 = score_2 - v.score
                            if score_lv < 1 and i == #data_need_2 and score_2 > 0 then
                                v.score = v.score + score_2
                            end
                        end
                        print('============data.setting.club_type=======================', i, #data_need_2, score_lv, v.score, v.score_old, score_2)
                        v.bean = v.score - data.setting.ji_fen_time
                        skynet.call("MG_SAVE", "lua", "update_bean_uid", v.uid, v)
                    end
                end
            end
            game_log_detail[data.game_log_id][data.number] = data.detail
        end
        local query_sql = string.format("update `pan_h5_games` set game_status=%d, participant='%s',result='%s',detail='%s',update_time='%s' where id=%d",
        game_status, json.encode(data.participant), json.encode(data.result), json.encode(game_log_detail[data.game_log_id]), time, data.game_log_id);
        local res = mysql_db_query(query_sql)
        if res and res.errno then
            if game_status > 2 then
                game_log_detail[data.game_log_id] = nil
                game_log_pan_h5_games_log[data.game_log_id] = nil
            end
        end
        return 1
    end
    return ok
end

--game_status 1	正在进行中，刚刚创建房间或游戏中
-- 2	上报每局游戏情况
-- 3	游戏取消，只创建房间未进行游戏
-- 4	游戏结束或者解散
function CMD.close_game_log(room_id)
    local query_sql = string.format("select id from `pan_h5_games` where room_id=%d and game_status < 3", room_id);
    local res = mysql_db_query(query_sql)
    if res ~= nil and res[1] ~= nil and res[1].id ~= nil and res[1].id > 0 then
        local game_log_id = res[1].id
        if game_log_pan_h5_games_log[game_log_id] ~= nil then
            game_log_pan_h5_games_log[game_log_id] = nil
        end
        if game_log_detail[game_log_id] ~= nil then
            game_log_detail[game_log_id] = nil
        end
        local query_sql = string.format("update `pan_h5_games` set game_status=3 where id=%d", game_log_id);
        local res = mysql_db_query(query_sql)

        skynet.call("MG_SAVE", "lua", "redis_hset", 'game_start', room_id, game_log_id)
    end
end

function CMD.sign(data)
    local tableTest = {}
    for i in pairs(data) do
        if i ~= nil then
            table.insert(tableTest, i)
        end
    end
    -- 升序
    -- table.sort(tableTest, function(a,b) return (a < b) end)  
    -- 降序
    table.sort(tableTest, function(a, b) return (a > b) end)
    -- 遍历
    local str = ''
    for _, fName in pairs(tableTest) do
        print(fName, data[fName])
        str = fName .. '=' .. data[fName] .. '&' .. str
    end
    print('===str==11=', str, string.sub(str, 0, -2))
    str = string.upper(md5.sumhexa(string.sub(str, 0, -2)))
    print('===str==22=', str)
    return str
end

function CMD.get_url_rs(domain, url, data, is_sign)
    if is_sign ~= nil and is_sign == 1 then
        data.sign = CMD.sign(data)
    end
    print('============get_url_rs====111===========', json.encode(data))
    local status, body = httpc.post(domain, url, data, {})
    if status == 200 then
        print('============get_url_rs===============', body)
        return json.decode(body)
    else
        return nil
    end
end

function CMD.get_fmc_token(domain, data)
    local SECRET_KEY = 'VS0ZQlXYRWdMR5mBRnTIAB8ww5TqD0ME'
    local CLIENT_ID = '2MDFuX8TdD3MS8Sn'
    local post_data = {
        client_id = CLIENT_ID,
        client_secret = SECRET_KEY,
        user_id = data.uid,
        nickname = data.name,
        avatar = data.head,
    }
    local rs = CMD.get_url_rs(domain, '/api/auth/user', post_data, 1)
    print('============get_fmc====111===========', json.encode(rs))
    return rs
end

function CMD.get_fmc_user_wallet(domain, data)
    if data.token == nil then
        data.token = CMD.get_fmc_token(domain, data)
    end
    local post_data = {
        token = data.token,
    }
    local rs = CMD.get_url_rs(domain, '/api/user/wallet', post_data, 1)
    print('============get_fmc====111===========', json.encode(rs))
    return rs
end

function CMD.get_fmc_coin_sub(domain, data)
    if data.token == nil then
        data.token = CMD.get_fmc_token(domain, data)
    end
    local SECRET_KEY = 'VS0ZQlXYRWdMR5mBRnTIAB8ww5TqD0ME'
    local CLIENT_ID = '2MDFuX8TdD3MS8Sn'
    local post_data = {
        client_id = CLIENT_ID,
        client_secret = SECRET_KEY,
        token = data.token,
        remark = data.remark, --备注
        value = data.value, --数值
    }
    local rs = CMD.get_url_rs(domain, '/api/coin/sub', post_data, 1)
    print('============get_fmc====111===========', json.encode(rs))
    return rs
end

-- 查询用户信息，pan_member 表
function CMD.get_member_info(uid, select_field)
    local query_sql = string.format("select " .. select_field .. "  from `pan_member` where uid = %d", uid)
    print("------------query_Sql---------------", query_sql)
    local sql_data = mysql_db_query(query_sql)
    print("---------------------------sql_data------------------", json.encode(sql_data))
    if sql_data ~= nil and sql_data[1] ~= nil then
        if sql_data[1]['is_vip'] ~= nil then
            if sql_data[1]['is_vip'] == 10 then
                sql_data[1]['vip_tilte'] = '我是俱乐部铜牌会员'
            elseif sql_data[1]['is_vip'] == 20 then
                sql_data[1]['vip_tilte'] = '我是俱乐部银牌会员'
            elseif sql_data[1]['is_vip'] == 30 then
                sql_data[1]['vip_tilte'] = '我是俱乐部金牌会员'
            else
                sql_data[1]['vip_tilte'] = "我是俱乐部普通会员"
            end
        end
    end
    return sql_data
end

-- 查询用户粉丝数量
function CMD.get_fans(uid)
    local query_sql = string.format("select  count(*) as fans_count from `pan_member` where tj_mid = %d", uid)
    local sql_data = mysql_db_query(query_sql)
    if sql_data ~= nil and sql_data[1] ~= nil and sql_data[1]['fans_count'] ~= nil then
        return sql_data[1]['fans_count']
    end
    return 0
end

-- 获取粉丝列表
function CMD.get_fans_info(uid, select_field, type, page, page_size)
    local query_sql
    if type == 1 then
        query_sql = string.format("select %s from `pan_member` where tj_mid = %d limit %d , %d", select_field, uid, page, page_size)
        print("--------------------------query_sql------------------------------", query_sql)
    else
        query_sql = string.format("SELECT n.openid,n.is_vip,n.uid,n.nickname,n.province,n.subscribe_time,n.headimgurl FROM `pan_member` m inner join `pan_member` n on m.uid=n.tj_mid WHERE m.`tj_mid` = %d  limit %d , %d ", uid, page, page_size)
        print("--------------------------query_sql------------------------------", query_sql)
    end

    local sql_data = mysql_db_query(query_sql)
    return sql_data
end

--  查询用户销售仓房卡  pan_sale_roomcard 表
function CMD.get_sale_roomcard(uid)
    local query_sql = string.format("select sale_roomcard from pan_sale_roomcard where uid = %d", uid)
    local sql_data = mysql_db_query(query_sql)
    if sql_data ~= nil and sql_data[1] ~= nil and sql_data[1]['sale_roomcard'] ~= nil then
        return math.floor(sql_data[1]['sale_roomcard']);
    else
        return 0;
    end
end

-- 查询用户游戏仓房卡  pan_game_room_card 表
function CMD.get_game_roomcard(uid)
    local query_sql = string.format("select room_card from pan_game_room_card where uid = %d", uid)
    local sql_data = mysql_db_query(query_sql)
    if sql_data ~= nil and sql_data[1] ~= nil and sql_data[1]['room_card'] ~= nil then
        return math.floor(sql_data[1]['room_card']);
    else
        return 0;
    end
end

-- 游戏仓房卡日志
function CMD.change_game_roomcard(uid, game_roomcard_change, message_id)
    mysql_db_query("begin")
    local game_roomcard = 0
    local query_sql = string.format("SELECT * FROM pan_game_room_card WHERE `uid`= %d LIMIT 1 FOR UPDATE", uid)
    local row = mysql_db_query(query_sql)
    print("--------------------------row--------------------------", json.encode(row))
    if row == nil or row[1] == nil then
        query_sql = string.format("insert into pan_game_room_card (uid,room_card) value(%d,0)", uid)
        local insert_res = mysql_db_query(query_sql)
        print("--------------------------insert_res--------------------------", json.encode(insert_res))
        query_sql = string.format("SELECT * FROM pan_game_room_card WHERE `uid`= %d LIMIT 1 FOR UPDATE", uid)
        row = mysql_db_query(query_sql)
    end

    if row ~= nil and row[1]['room_card'] ~= nil then
        game_roomcard = row[1]['room_card']
    end

    local game_roomcard_after = game_roomcard_change + game_roomcard
    if game_roomcard_after < 0 then
        return 0
    end

    local insert_id = 0
    local log_table = string.format("pan_game_room_card_log_%d", (uid % 10))

    query_sql = string.format("insert into `%s` (uid,room_card_change,room_card_after,message_id,create_time)value(%d,%d,%d,%d,'%s')",
    log_table, uid, game_roomcard_change, game_roomcard_after, message_id, os.date("%Y-%m-%d %H:%M:%S"))
    local insert_res = mysql_db_query(query_sql)
    print("-------------------------------change_game_roomcard insert_res------------------------", json.encode(insert_res))
    if insert_res ~= nil and insert_res['insert_id'] ~= nil and insert_res['insert_id'] > 0 then
        query_sql = string.format("update pan_game_room_card set room_card = %d where uid = %d", game_roomcard_after, uid)
        local update_res = mysql_db_query(query_sql)
        print("-------------------------------change_game_roomcard update_res------------------------", json.encode(update_res))
        if update_res['errno'] == nil then
            mysql_db_query("commit")
            return insert_res['insert_id']
        else
            return 0
        end
    else
        mysql_db_query("rollback")
        return 0
    end

end

-- 查询用户剩余QC  pan_qc 表
function CMD.get_qc(uid)
    local query_sql = string.format("select qc_coins from pan_qc where uid = %d", uid)
    local sql_data = mysql_db_query(query_sql)
    if sql_data ~= nil and sql_data[1] ~= nil and sql_data[1]['qc_coins'] ~= nil then
        return math.floor(sql_data[1]['qc_coins']);
    else
        return 0;
    end
end

-- 查询用户剩余金币  pan_jb 表
function CMD.get_jb(uid)
    local jb_in
    local jb_out
    local jb_left

    --统计入账金额
    local query_sql = string.format("select sum(amount) as amount from pan_jb where uid = %d and type > 0 and state >0", uid)
    local sql_data = mysql_db_query(query_sql)
    if sql_data ~= nil and sql_data[1] ~= nil and sql_data[1]['amount'] ~= nil then
        jb_in = sql_data[1]['amount'];
    else
        jb_in = 0;
    end

    --统计出账金额
    query_sql = string.format("select sum(amount) as amount from pan_jb where uid = %d and type < 0 and state >0", uid)
    sql_data = mysql_db_query(query_sql)
    if sql_data ~= nil and sql_data[1] ~= nil and sql_data[1]['amount'] ~= nil then
        jb_out = sql_data[1]['amount'];
    else
        jb_out = 0;
    end

    jb_left = jb_in - jb_out
    if jb_left > 0 then
        return jb_left
    else
        return 0
    end
end

--获取创建俱乐部列表 club 表
function CMD.create_club_list(uid, page, page_size)
    local query_sql = string.format("select * from `club` where uid = %d limit %d , %d ", uid, page, page_size)
    local sql_data = mysql_db_query(query_sql)
    return sql_data
end

--获取加入俱乐部列表
function CMD.join_club_list(uid, page, page_size)
    local select_field = "u.uid,u.club_id,u.type,u.time,c.uid as club_uid,c.user_now,c.club_num,c.club_name,c.text,c.club_type,c.game_type"
    local query_sql = string.format("select %s from `club_user` as u  left join club as c on u.club_id = c.club_id  where u.uid = %d order by u.id desc limit %d , %d", select_field, uid, page, page_size)
    print("----------------------------query_sql--------------------------", query_sql)
    local sql_data = mysql_db_query(query_sql)
    return sql_data
end

--判断手机号是否存在
function CMD.check_phone(phone)
    local query_sql = string.format("select phone,uid from pan_member where phone = %s", phone)
    print("-----------------------------sql---------------------", query_sql)
    local sql_data = mysql_db_query(query_sql)
    return sql_data
end

--修改数据  update_table_name 表名 update_data 修改的字段和值  where_data 条件
function CMD.update_info(update_table_name, update_data, where_data)
    local update_filed_sql
    local where_sql

    if update_data ~= nil then
        for k, v in pairs(update_data) do
            if update_filed_sql == nil then
                update_filed_sql = k .. "=" .. v .. ","
            else
                update_filed_sql = update_filed_sql .. k .. "=" .. v .. ","
            end
        end
        update_filed_sql = string.sub(update_filed_sql, 1, -2)
    end

    if where_data ~= nil then
        for k, v in pairs(where_data) do
            if where_sql == nil then
                where_sql = k .. "=" .. v .. "  and  "
            else
                where_sql = where_sql .. k .. "=" .. v .. "  and  "
            end
        end
        where_sql = where_sql .. " 1=1"
    end
    if update_filed_sql ~= nil and where_sql ~= nil then
        local query_sql = string.format("update %s set %s where %s ", update_table_name, update_filed_sql, where_sql)
        local sql_data = mysql_db_query(query_sql)
        return sql_data
    else
        return TRUE;
    end
end

--获取用户剩余荷包
function CMD.get_money(uid)
    local query_sql = string.format("select money from pan_money where uid = %d", uid)
    local sql_data = mysql_db_query(query_sql)
    if sql_data ~= nil and sql_data[1] ~= nil and sql_data[1]['money'] ~= nil then
        return sql_data[1]['money']
    else
        return 0
    end

end

--money日志
function CMD.change_money(uid, money_change, msg_id, ukey, correlation_id)
    mysql_db_query("begin")
    local money = 0
    local query_sql = string.format("SELECT * FROM pan_money WHERE `uid`= %d LIMIT 1 FOR UPDATE", uid)
    local row = mysql_db_query(query_sql)
    if row == nil or row[1] == nil then
        query_sql = string.format("insert into pan_money (uid,money) value(%d,0)", uid)
        mysql_db_query(query_sql)
        query_sql = string.format("SELECT * FROM pan_money WHERE `uid`= %d LIMIT 1 FOR UPDATE", uid)
        row = mysql_db_query(query_sql)
    end

    if row ~= nil and row[1]['money'] ~= nil then
        money = row[1]['money']
    end

    local money_after = money_change + money
    if money_after < 0 then
        return 0
    end

    local log_table = string.format("pan_money_log_%d", (uid % 10))
    query_sql = string.format("select id from %s where ukey = %s limit 1", log_table, ukey)
    row = mysql_db_query(query_sql)
    print("----------------row---------------", json.encode(row))
    if row == nil or row[1] == nil then
        query_sql = string.format("insert into `%s` (uid,money_change,money_after,message_id,ukey,correlation_id,mktime)value(%d,%d,%d,%d,'%s','%s','%s')",
        log_table, uid, money_change, money_after, msg_id, ukey, correlation_id, os.date("%Y-%m-%d %H:%M:%S"))
        print("----------------query_sql_insert---------------", query_sql)
        local insert_res = mysql_db_query(query_sql)

        if insert_res ~= nil and insert_res['insert_id'] ~= nil and insert_res['insert_id'] > 0 then
            query_sql = string.format("update pan_money set money = %d where uid = %d", money_after, uid)
            local update_res = mysql_db_query(query_sql)
            if update_res['errno'] == nil then
                mysql_db_query("commit")
                return insert_res['insert_id']
            else
                return 0
            end

        else
            mysql_db_query("rollback")
            return 0
        end
    else
        print("---------------------------rownil------------------------------")
        return 0
    end
end

--获取我的荷包日志
function CMD.get_money_log(uid, page, page_size)
    local table_name
    table_name = "pan_money_log_" .. (uid % 10)
    local query_sql = string.format("select id,money_change,message_id, status,mktime from %s where message_id != -1 and uid = %d order by mktime desc limit %d , %d", table_name, uid, page, page_size)
    print("--------------------------------------query_sql-------------------------", query_sql)
    local sql_data = mysql_db_query(query_sql)
    return sql_data
end

--战绩列表
function CMD.get_game_record_list(uid, page, page_size, type)
    local log_table = string.format("pan_h5_games_log_%d", (uid % 10))
    print("-------------------------------log_table--------------------------", log_table)
    local query_sql
    local query_condition

    if type == 1 then
        query_condition = " and 1=1 "
    elseif type == 2 then
        query_condition = "and `game_table` . `game_status` IN (1,2) "
    elseif type == 3 then
        query_condition = string.format(" and `game_Table` . `creator_mid` = %d ", uid)
    elseif type == 4 then
        query_condition = string.format(" and `game_table`.`creator_mid` != %d ", uid)
    end

    print("------------------------------query_condition-------------------------------", query_condition)
    query_sql = string.format("SELECT * FROM  `%s` AS `mid_table` LEFT JOIN `pan_h5_games` AS `game_table` ON `mid_table`.`game_id`=`game_table`.`id` WHERE `mid_table`.`uid`= %d  %s ORDER BY `mid_table`.`game_id` DESC  LIMIT  %d,%d", log_table, uid, query_condition, page, page_size)
    print("------------------------------query_sql-------------------------------", query_sql)
    local sql_data = mysql_db_query(query_sql)

    return sql_data
end

--战绩详情
function CMD.get_game_record_detail(game_id)
    local query_sql = string.format("select * from pan_h5_games where id = %d", game_id)
    print("------------------------------query_sql-------------------------------", query_sql)
    local sql_data = mysql_db_query(query_sql)
    return sql_data
end

--获取商品信息
function CMD.get_goods_info(goods_id)
    local query_sql = string.format("select name,price,roomcard,coins from pan_goods where goods_id = %d and is_onsale = 1", goods_id)
    local sql_data = mysql_db_query(query_sql)
    return sql_data
end

--创建订单
function CMD.create_bill(uid, tj_mid, amount, number, address_id, state, goods_id)
    local insert_id = 0
    local query_sql = string.format("insert into pan_bill(uid,tj_mid,amount,number,address_id,state,goods_id,mktime)value(%d,%d,%d,%d,%d,%d,%d,'%s')", uid, tj_mid, amount, number, address_id, state, goods_id, os.date("%Y-%m-%d %H:%M:%S"))
    print("---------------------query_sql----------------------", query_sql)
    local sql_data = mysql_db_query(query_sql)
    print("---------------------sql_data----------------------", json.encode(sql_data))
    if sql_data ~= nil and sql_data['insert_id'] ~= nil then
        insert_id = sql_data['insert_id']
    end

    return insert_id
end

skynet.start(function()
    start_mysql(mysql_args)
    httpc.dns()	-- set dns server 
    skynet.dispatch("lua", function(_, _, command, ...)
        local f = CMD[command]
        -- if f == nil then
        --     print('undefined CMD' .. command)
        -- end
        skynet.error("-- login ------->  do CMD." .. command)
        skynet.ret(skynet.pack(f(...)))
    end)
    skynet.register "LOGIN"
end)